import type { AxiosRequestConfig, AxiosResponse } from "axios";
import axios from "axios";

let userStore: ReturnType<typeof userStoreWithout>;

const inst = axios.create({
    baseURL: "/"
});

inst.interceptors.request.use((config) => {
    return config;
});
inst.interceptors.response.use(
    (resp) => {
        if (resp.status === 200) {
            return resp.data;
        } else {
            return Promise.reject(resp);
        }
    },
    (error) => {
        if (error.status === 401) {
            // 401 未授权，跳转登录页
            if (!userStore) {
                userStore = userStoreWithout();
            }
            userStore.token = "";
            userStore.info = {};
            userStore.current = {
                isLogin: false
            };
            return userStore.clear();
            // return Promise.reject(resp);
        } else {
            const response = {} as AxiosResponse;
            response.config = error.config;
            response.data = null;
            response.headers = error.config.headers;
            response.status = error.code;
            response.statusText = error.message;
            response.request = error.request;
            return Promise.reject(response);
        }
    }
);

function http<T = any>(options: AxiosRequestConfig): Promise<GotResponse<T>> {
    return inst(options);
}

export const got = Object.assign(
    <T = any>(options: AxiosRequestConfig) => {
        return http<T>(options);
    },
    {
        get<T = any>(
            url: string,
            params: Record<string, string | number | boolean> = {},
            config?: AxiosRequestConfig
        ) {
            return http<T>({ url, ...config, params, method: "get" });
        },
        post<T = any>(
            url: string,
            data: Record<string, string | number | boolean> = {},
            config?: AxiosRequestConfig
        ) {
            return http<T>({ url, ...config, data, method: "post" });
        },
        put<T = any>(
            url: string,
            data: Record<string, string | number | boolean> = {},
            config?: AxiosRequestConfig
        ) {
            return http<T>({ url, ...config, data, method: "put" });
        },
        delete<T = any>(url: string, config?: AxiosRequestConfig) {
            return http<T>({ url, ...config, method: "delete" });
        }
    }
);

interface GotResponse<T = any> {
    code: number;
    data: T;
    message: string;
    success: boolean;
    timestamp: number;
}
